/**
 * @format
 * @Author: TC
 * @Date: 2023-02-17 23:34:49
 * @Last Modified by: TC
 * @Last Modified time: 2025-06-19 15:49:40
 */

import { IBaseInterface } from "../../Interface/BaseInterface";
import { ITimerInstance } from "./TimerInterface";

/**
 * 定时器单位
 */
export class TimerUnit implements IBaseInterface {
    private _time: number = 0;
    private _timeId: number = -1; //定时器id
    private _delay: number = 0;
    private _executeTimes: number = 0;
    private _currTimes: number = 0;
    private _interval: number = 0;
    private _completed: boolean = false;
    private _callback: Function = null;
    private _thisObj: any;
    private _arg: any;
    private _paused: boolean = false;

    constructor(iTimer: ITimerInstance) {
        this._timeId = iTimer.timerId;
        this._interval = iTimer.interval;
        this._executeTimes = iTimer.executeTimes;
        this._callback = iTimer.callback;
        this._thisObj = iTimer.thisObj;
        this._arg = iTimer.arg;
        this._delay = iTimer.delayTime;

        iTimer = null;
    }

    public update(dt: number): void {
        //暂停中
        if (this._paused) return;
        if (this._delay > 0) {
            this._delay -= dt;
            return;
        }
        //正常执行
        this._time += dt;
        if (this._time > this._interval) {
            this.execute(this._time);
            this._time = 0;
            this._currTimes++;
            if (this._currTimes === this._executeTimes) {
                this._completed = true;
            }
        }
    }

    private execute(dt: number) {
        this._callback.call(this._thisObj, dt, this._arg);
    }

    /**
     * 暂停
     */
    public pause(): void {
        this._paused = true;
    }

    /**
     * 恢复
     */
    public resume(): void {
        this._paused = false;
    }

    public get timerId(): number {
        return this._timeId;
    }

    public get completed(): boolean {
        return this._completed;
    }

    release(): void {
        this._callback = null;
        this._thisObj = null;
        this._arg = null;
    }
}
